<template>
  <div ref="Wrapper" class="canvas-signature_wrapper" :style="wrapperStyle">
    <canvas id="canvas-signature-canvas" />
    <div v-if="isMax" class="canvas-signature_tool">
      <span class="canvas-signature_clear" @click="onClickClear">
        <van-icon name="replay" />
      </span>
      <van-button round size="small" native-type="button" @click="onClickCancel">取消</van-button>
      <van-button round type="primary" size="small" native-type="button" @click="onClickConfirm"
        >完成</van-button
      >
    </div>
  </div>
</template>

<script>
import { Button, Icon } from 'vant';

import Draw from './lib/draw';

/** 默认的模式 */
const MODE_DEFAULT = 'normal';

/** CANVAS_ID */
const CANVAS_ID = 'canvas-signature-canvas';

export default {
  name: 'CanvasSignature',

  components: {
    'van-button': Button,
    'van-icon': Icon,
  },

  props: {
    /**
     * 画布模式，支持 `'normal'|'max'`
     *
     * @default `normal`
     */
    mode: {
      type: String,
      default: MODE_DEFAULT,
    },
  },

  data() {
    return {
      /** 外层包裹元素的样式，可能会旋转 */
      wrapperStyle: {},
    };
  },

  computed: {
    /**
     * 画布旋转角度
     */
    degree() {
      return this.mode === MODE_DEFAULT ? 0 : 90;
    },

    /**
     * 是否是最大的模式
     */
    isMax() {
      return this.mode !== MODE_DEFAULT;
    },
  },

  watch: {
    /**
     * 画布角度/模型变了，需要你重新初始化外层的样式
     */
    degree() {
      this.initSignature();
    },
  },

  mounted() {
    this.initSignature();
  },

  methods: {
    /**
     * 初始化外部的样式
     */
    initWrapperStyle() {
      if (this.mode === 'max') {
        try {
          const pEle = this.$refs.Wrapper.parentElement;

          const w = pEle.clientWidth;
          const h = pEle.clientHeight;
          const length = (h - w) / 2;

          this.wrapperStyle = {
            transform: `rotate(${this.degree}deg) translate(${length}px,${length}px)`,
            width: `${h}px`,
            height: `${w}px`,
            transformOrigin: 'center center',
          };
        } catch (error) {
          this.wrapperStyle = {};
        }
      } else {
        this.wrapperStyle = {};
      }
    },

    /**
     * 初始化画布
     */
    initCanvas() {
      this.$nextTick(() => {
        const oldCanvas = document.querySelector('#' + CANVAS_ID);

        if (oldCanvas) {
          // 删除旧的画布
          this.$refs.Wrapper.removeChild(oldCanvas);
        }

        const DOM_CC = document.createElement('canvas');

        DOM_CC.id = CANVAS_ID;

        this.$refs.Wrapper.appendChild(DOM_CC);

        // 等待 popup 300ms 过度动画完成后再初始化
        setTimeout(() => {
          this.draw = new Draw(document.querySelector('#' + CANVAS_ID), -this.degree);
        }, 300);
      });
    },

    /**
     * 初始化签名相关工作
     */
    initSignature() {
      // 初始化外层样式
      this.initWrapperStyle();

      // 初始化画布
      this.$nextTick(() => {
        this.initCanvas();
      });
    },

    /**
     * 清空画布
     */
    clear() {
      this.draw.clear();
    },

    /**
     * 获取 PNG 图片
     */
    getPNGImage() {
      return this.draw.getPNGImage();
    },

    /**
     * 获取 JPG 图片
     */
    getJPGImage() {
      return this.draw.getJPGImage();
    },

    /**
     * base 64 图片转成 Blob 文件
     * @param {string} dataURL 图片地址
     */
    dataURLtoBlob(dataURL) {
      return this.draw.dataURLtoBlob(dataURL);
    },

    /**
     * 点击清空画布
     */
    onClickClear() {
      this.clear();
    },

    /**
     * 点击取消
     */
    onClickCancel() {
      this.$emit('cancel');
    },

    /**
     * 点击确定
     */
    onClickConfirm() {
      this.$emit('confirm');
    },
  },
};
</script>

<style lang="less">
@import '~vant/lib/style/var.less';
@import '~@scf/ding-style-less/var.less';

.canvas-signature_wrapper {
  width: 100%;
  height: 100%;
  display: flex;
  position: relative;

  canvas {
    flex: 1;
    position: relative;
    z-index: 298;
  }
}

.canvas-signature_tool {
  position: absolute;
  bottom: @padding-content;
  right: @padding-content;
  display: flex;
  align-items: center;
  z-index: 299;

  .van-button {
    margin-left: 20px;
  }
}

.canvas-signature_clear {
  width: 20px;
  height: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: @color-title;
  font-size: 16px;
}
</style>
